package seismosurfer.gui.menuitem;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import seismosurfer.domain.Export;
import seismosurfer.util.SeismoException;
import seismosurfer.util.Util;

import com.bbn.openmap.gui.menu.MapHandlerMenuItem;

/**
 * This menu item shows a dialog box to save the earthquake
 * data in a text format.
 *
 */
public class ExportMenuItem extends MapHandlerMenuItem implements
        ActionListener {
    
    private static final long serialVersionUID = -3220200854147545594L;

    protected Export export;

    public ExportMenuItem(String title, int exportType) {
        super(title);
        export = Export.makeExport(exportType);
        addActionListener(this);
    }

    public void actionPerformed(ActionEvent actionEvent) {

        PrintWriter out = null;

        try {
            while (true) {

                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(new ExportFileFilter());

                int returnVal = chooser.showSaveDialog(getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    String filename = chooser.getSelectedFile()
                            .getAbsolutePath();

                    filename = checkFileName(filename, export.getExtension());
                    if (filename == null) {
                        // This is the reason for the while
                        // loop, the name didn't really pass
                        // muster, so we'll try again.
                        continue;
                    }

                    out = Util.getBuffWriter(filename);

                    export.doExport(out);

                    break;
                } else if (returnVal == JFileChooser.CANCEL_OPTION) {
                    break;
                }
            }
        } catch (IOException ex) {
            throw new SeismoException(ex);
        }
    }
    
    /**
     * A FileFilter extension to let only files
     * associated with one of the export formats
     * of Seismo-Surfer appear in the directory listing.
     *
     */
    public class ExportFileFilter extends FileFilter {

        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = Util.getExtension(f);
            if (extension != null) {
                if (extension.equals(export.getExtension())) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }
        
        public String getDescription() {
            return export.getDescription();
        }

    }

    /**
     * A little method that checks the file path to see if it exists, and
     * modifies it with the suffix if it doesn't have one specified by the user.
     * Asks the user if it's OK to overwrite if the file exists.
     * 
     * @param filePath
     *            absolute file path to check.
     * @param suffix
     *            suffix to append to filePath if it doesn't already have one.
     *            This word should not contain a starting '.'.
     * @return null if name is no good, a String to use if good.
     */
    protected String checkFileName(String filePath, String suffix) {

        String fileName = filePath.substring(filePath
                .lastIndexOf(File.separator));
        String newFilePath;

        if (fileName.indexOf('.') == -1) {
            newFilePath = filePath + "." + suffix;
        } else {
            // else leave it alone, user specified suffix
            newFilePath = filePath;
        }

        File file = new File(newFilePath);
        if (file.exists()) {
            // Check to see if it is alright to overwrite.
            int choice = JOptionPane.showConfirmDialog(null, "The file "
                    + newFilePath + " exists, replace?",
                    "Confirm File Replacement", JOptionPane.YES_NO_OPTION);
            if (choice != JOptionPane.YES_OPTION) {
                newFilePath = null;
            }
        }

        return newFilePath;
    }

}